package com.example.service;

import cn.hutool.core.date.DateUtil;
import com.example.common.enums.ResultCodeEnum;
import com.example.entity.Account;
import com.example.entity.ActivitySign;
import com.example.exception.CustomException;
import com.example.mapper.ActivitySignMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 作者：风中叶
 * 功能：活动报名业务处理
 */

@Service
public class ActivitySignService {

    @Autowired
    ActivitySignMapper activitySignMapper;


    /**
     * 新增报名活动
     */
    public void add(ActivitySign activitySign) {
        Account currentUser = TokenUtils.getCurrentUser();
        // 查询当前用户是否已经报名
        ActivitySign as = this.selectByActivityIdAndUserId(activitySign.getId(), currentUser.getId());
        if (as != null) {
            throw new CustomException(ResultCodeEnum.ACTIVITY_SIGN_ERROR);
        }
        activitySign.setUserId(currentUser.getId());  // 设置参加活动用户名称
        activitySign.setTime(DateUtil.now());  // 设置报名时间
        activitySignMapper.insert(activitySign);
    }

    /**
     * 根据活动id和用户id查询报名活动
     */
    public ActivitySign selectByActivityIdAndUserId(Integer actId, Integer userId) {
        return activitySignMapper.selectByActivityIdAndUserId(actId, userId);
    }

    /**
     * 分页查询
     */
    public PageInfo<ActivitySign> selectPage(ActivitySign activitySign, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ActivitySign> list = activitySignMapper.selectAll(activitySign);
        return PageInfo.of(list);
    }

    public void deleteById(Integer id) {
        activitySignMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            activitySignMapper.deleteById(id);
        }
    }

    /**
     *用户取消报名
     */
    public void userDelete(Integer activityId, Integer userId) {
        activitySignMapper.userDelete(activityId, userId);
    }
}
